import { NavBar, Input, TextArea, type InputRef, type TextAreaRef } from 'antd-mobile'
import styles from './index.module.scss'
import { useAppSelector } from '@/store'
import { useEffect, useRef, useState } from 'react'

interface Props {
  hideInput: (type: 'name' | 'intro') => void
  type: 'name' | 'intro'
  onUpdate: (type: 'name' | 'intro', value: string) => void
}
export default function EditInput({ hideInput, type, onUpdate }: Props) {
  // 个人资料信息获取
  const { userProfile } = useAppSelector((state) => state.loginSlice)
  // 输入框表单值
  const [value, setValue] = useState(type === 'name' ? userProfile.name : userProfile.intro)
  // 输入框ref
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  // 自动聚焦
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  return (
    <>
      <div className={styles.root}>
        <NavBar
          className="navbar"
          right={
            <span className="commit-btn" onClick={() => onUpdate(type, value)}>
              提交
            </span>
          }
          onBack={() => hideInput(type)}
        >
          编辑{type === 'name' ? '昵称' : '简介'}
        </NavBar>
        <div className="edit-input-content">
          <h3>编辑{type === 'name' ? '昵称' : '简介'}</h3>
          {type === 'name' ? (
            <div className="input-wrap">
              <Input
                ref={inputRef}
                placeholder="请输入昵称"
                value={value}
                onChange={(e) => setValue(e)}
                maxLength={11}
              ></Input>
            </div>
          ) : (
            <TextArea
              ref={textRef}
              className="textarea"
              placeholder="请输入简介"
              showCount
              value={value}
              maxLength={99}
              onChange={(e) => setValue(e)}
            ></TextArea>
          )}
        </div>
      </div>
    </>
  )
}
